package flyshoes.service;

import flyshoes.mybatis.entity.Product;
import flyshoes.mybatis.entity.Result;
import flyshoes.mybatis.entity.ShoppingCart;
import flyshoes.mybatis.service.serviceImpl.ProductServiceImpl;
import flyshoes.mybatis.service.serviceImpl.ShoppingcartServiceImpl;
import flyshoes.utils.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class CartServiceImpl {
    private final ShoppingcartServiceImpl cartService;
    private final ProductServiceImpl productService;
    private final RedisTemplate redisTemplate;
    @Transactional
    public Result getCart(){  //查找购物车
        Integer userId = ThreadLocalUtil.get();
        List<ShoppingCart> listCart = cartService.lambdaQuery().eq(ShoppingCart::getUserId,userId).list();
        if (listCart.isEmpty()){
            return Result.success("暂无商品");
        }
        List<Map> list = new ArrayList<>();
        for (ShoppingCart cart : listCart) {
            Product product = productService.lambdaQuery().eq(Product::getId,cart.getProductId()).one();
            Map map = new HashMap<>();
            map.put("cartInfo",cart);
            map.put("productInfo",product);
            list.add(map);
        }
        redisTemplate.opsForValue().set("cartInfo:"+userId,list,168, TimeUnit.HOURS);
        return Result.success(list);
    }
    @Transactional
    public Result addCart(ShoppingCart cart) { //增加商品到购物车
       //1.判断库存是否足够
        Product product = productService.lambdaQuery().eq(Product::getId, cart.getProductId()).one();
        if (cart.getQuantity() <= product.getStockQuantity()) {
            Integer userId = ThreadLocalUtil.get();
            //2.根据userID判断购物车是否为空
            List<ShoppingCart> cartDb = cartService.lambdaQuery().eq(ShoppingCart::getUserId, userId).list();
            if (cartDb.isEmpty()) {
                //2.1如果为空，直接进行操作
                cart.setUserId(userId);
                cart.setTotalPrice(product.getPrice() * cart.getQuantity());
                cart.setCreatedTime(LocalDateTime.now());
                cartService.save(cart);
                return Result.success("加入购物车成功");
            } else {
                //2.2否则进行遍历商品
                for (ShoppingCart shoppingCart : cartDb) {
                    if (shoppingCart.getProductId().equals(cart.getProductId())){
                        //使用 equals() 方法而不是 ==，因为 == 比较的是引用而不是值。
                        //2.3商品已在购物车
                        return Result.fail(400,"此商品已在购物车");
                    }
                }
                // 2.4 如果遍历完都没有找到，添加商品到购物车
                cart.setUserId(userId);
                cart.setTotalPrice(product.getPrice() * cart.getQuantity());
                cart.setCreatedTime(LocalDateTime.now());
                cartService.save(cart);
                return Result.success("加入购物车成功");
            }
        }
           return Result.fail(400, "加入失败，库存不足");
    }
    @Transactional
    public Result removeShoesInCart(Integer productId){ //通过productId移除购物车里的商品
        Integer userId = ThreadLocalUtil.get();
        ShoppingCart productDb = cartService.lambdaQuery()
                .eq(ShoppingCart::getUserId,userId)
                .eq(ShoppingCart::getProductId,productId)
                .one();
        boolean b = cartService.removeById(productDb);
        if (!b){
            return Result.fail("移除失败");
        }
        return Result.success("移除成功");
    }
    @Transactional
    public Result removeByCartIds(List<Integer> cartIds){  //通过cartId批量移除购物车里单个或多个商品

        boolean b = cartService.removeByIds(cartIds);

        if (!b){
            return Result.fail("移除失败");
        }
        return Result.success("移除成功");
    }
    @Transactional
    public Result updateQuantity(Integer productId,Integer quantity){ //更新商品数量
        Integer userId = ThreadLocalUtil.get();
       boolean b = cartService.lambdaUpdate()
                .eq(ShoppingCart::getUserId,userId)
                .eq(ShoppingCart::getProductId,productId)
                .set(ShoppingCart::getQuantity,quantity)
                .update();
        if (!b){
            return Result.fail("更新数量失败");
        }
        return  Result.success("更新数量成功");
    }
}
